package cas.server;

import java.sql.*;

// 方便数据库增删改查的工具类
public class DB {

    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/websso?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String JDBC_USER = "root";
    private static final String JDBC_PWD = "123456";
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Can't register driver!");
        }
    }

    private DB () {}

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PWD);
    }

    @FunctionalInterface
    public interface QueryConsumer {
        void accept(ResultSet rs) throws SQLException;
    }

    public static void query(QueryConsumer consumer, String query, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(query);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        consumer.accept(resultSet);
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

    @FunctionalInterface
    public interface UpdateConsumer {
        void accept(int affectedRows) throws SQLException;
    }

    public static void update(UpdateConsumer consumer, String update, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(update);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        consumer.accept(preparedStatement.executeUpdate());
        preparedStatement.close();
        connection.close();
    }

}
